import asyncio
from fastapi import WebSocketDisconnect, WebSocket
from common.log import LOG, LogLevel


async def read_and_send_stdout(websocket: WebSocket, stream, stream_name):
    try:
        while True:

            line = await stream.readline()
            if not line:
                break
            decoded_line = line.decode('utf-8', errors='replace')
            await websocket.send_json({
                "status": "listening",
                "stream": stream_name,
                "details": decoded_line.strip()
            })
    except (WebSocketDisconnect, RuntimeError):
        LOG(LogLevel.DEBUG) << "客户端断开，stdout监控任务取消！" << "\n" 


async def read_and_send_stderr(websocket: WebSocket, stream, stream_name):
    """
    一次性读取流中的所有内容并发送，同时响应停止事件
    
    Args:
        websocket: WebSocket 连接
        stream: 异步流对象 (stdout/stderr)
        stream_name: 流名称标识 ("STDOUT"/"STDERR")
        stop_event: 停止事件信号
    """
    try:
        buffer = ""

        while True:
            # 尝试读取数据（带超时避免永久阻塞）
            try:
                line = await asyncio.wait_for(stream.readline(), timeout=0.1)
                if not line:  # 流已结束
                    break
                decoded = line.decode('utf-8', errors='replace').strip()
                buffer += decoded + "\n"
            except asyncio.TimeoutError:
                continue  # 继续检查停止信号
        # 一次性发送所有缓冲数据（如果需要）
        if buffer:
            await websocket.send_json({
                "status": "complete",
                "stream": stream_name,
                "data": "".join(buffer),
            })
    except (WebSocketDisconnect, RuntimeError):
        LOG(LogLevel.DEBUG) << "客户端断开，stderr监控任务取消！" << "\n" 
    
            

# 生成监控脚本
async def make_script(factors: list[dict]):
    pass


# 运行脚本文件
async def run_script(filename: str):
    pass


async def watch_for_stop(websocket, stop_event):
    try:
        while True:
            try:
                data = await asyncio.wait_for(websocket.receive_json(), timeout=0.5)
                if data.get("command") == "stop":
                    stop_event.set()
                    await websocket.send_json({"message": "接收到终止信号"})
                    return
            except asyncio.TimeoutError:
                continue
    except (WebSocketDisconnect, RuntimeError):
        pass
    except Exception as e:
        LOG(LogLevel.ERROR) << f"监控stop任务发生异常: {str(e)}" << "\n"
        pass